package cn.net.dpi.core.validation;

import cn.net.dpi.core.annotation.EnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Copyright(c) 2021 Dayou Positioning Intelligence Co.,Ltd
 * All rights reserved.
 * <p>
 * 枚举校验注解处理类
 *
 * @Date 2021/11/25
 * @Author changguoshan (changguoshan@dayoupi.cn)
 * @Version 0.2
 * @Reviewer
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
    private String[] strValues;
    private int[] intValues;

    /**
     * 初始化注解
     *
     * @param constraintAnnotation 注解枚举值
     */
    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
    }

    /**
     * 将注解枚举值校验
     *
     * @param value                      枚举值
     * @param constraintValidatorContext 校验规则
     * @return 是否校验通过
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (int s : intValues) {
                if (s == (Integer) value) {
                    return true;
                }
            }
        }
        return false;
    }
}
